package com.kgc.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 请求、响应中文乱码处理过滤器
 */
@WebFilter(filterName = "EncodingFilter", urlPatterns = "/*")
public class EncodingFilter implements Filter {

    // 静态资源白名单 (处理后缀)
    private List<String> staticTypes = Arrays
            .asList(".css", ".js", ".ico", ".png", ".jpg",
                    ".bmp", ".svg", ".less", ".scss", ".json", ".woff", ".otf", ".eot", ".ttf", ".woff2");

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 请求url
        String requestURI = request.getRequestURI();
        // 请求编码处理
        request.setCharacterEncoding("UTF-8");
        // 响应中文编码处理，非中文?
        for (String staticType : staticTypes) {
            if (requestURI.endsWith(staticType)) {
                // 不处理 放行
                chain.doFilter(request, response); // 目标请求服务器(=>LoginServlet)
                return;
            }
        }
        // 带中文的请求
        response.setContentType("text/html;charset=UTF-8");
        // 放行(代理模式) 通知LoginServlet执行
        chain.doFilter(request, response); // 目标请求服务器(=>LoginServlet)
    }
}
